import React, {useEffect, useState} from 'react';
import {
  DoneTab,
  PendingTab,
  TodoTab,
} from '../features/todo/Todo';
import {AppDispatch} from '../app/store';
import {useDispatch} from 'react-redux';
import {
  addTodo,
  fetchTodos,
  optimisticAddTodo,
  Todo,
} from '../features/todo/todoSlice';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';
import {Alert, Text, TextInput, TouchableOpacity, View} from 'react-native';
const Tab = createMaterialTopTabNavigator();

const HomeScreen = () => {
  const dispatch = useDispatch<AppDispatch>();
  const [task, setTask] = useState('');

  useEffect(() => {
    console.log('HomeScreen useEffect');
    dispatch(fetchTodos());
  }, [dispatch]);
  const handleAdd = () => {
    if (!task.trim()) {
      Alert.alert('请输入任务内容');
      return;
    }
    const now = new Date();
    const newTodo: Todo = {
      _id:"tmpid", // 临时 ID
      task: task.trim(),
      state: 'todo',
      startTime: now.toISOString(),
      endTime: new Date(now.getTime() + 60 * 60 * 1000).toISOString(), // +1小时
    };

    dispatch(optimisticAddTodo(newTodo)); // 前端立即显示
    dispatch(
      addTodo({
        task: newTodo.task,
        state: newTodo.state,
        startTime: newTodo.startTime,
        endTime: newTodo.endTime,
      }),
    ); // 同步后端
    setTask('');
  };
  return (
    <View style={{flex: 1}}>
      <View className="flex-row justify-between items-center p-8 bg-white">
        <TextInput
          className="flex-1 h-10 rounded border border-gray-300 pl-2"
          placeholder="type task"
          value={task}
          onChangeText={setTask}
        />
        <TouchableOpacity
          className="bg-blue-500 h-10 w-20 rounded items-center justify-center ml-2"
          onPress={handleAdd}>
          <Text className="text-white">ADD</Text>
        </TouchableOpacity>
      </View>

      <Tab.Navigator>
        <Tab.Screen name="Todo" component={TodoTab} />
        <Tab.Screen name="Pending" component={PendingTab} />
        <Tab.Screen name="Done" component={DoneTab} />
      </Tab.Navigator>
    </View>

    // </View>
  );
};

export default HomeScreen;
